package com.example.warehouse.contrallor;

import com.example.warehouse.entity.InStore;
import com.example.warehouse.entity.Purchase;
import com.example.warehouse.entity.Result;
import com.example.warehouse.entity.Store;
import com.example.warehouse.page.Page1;
import com.example.warehouse.service.InstoreService;
import com.example.warehouse.service.StoreService;
import com.example.warehouse.service.purchaseService;
import com.example.warehouse.utils.CurrentUser;
import com.example.warehouse.utils.TokenUtils;
import com.example.warehouse.utils.WarehouseConstants;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/purchase")
public class contrallorPurchase {

    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private purchaseService purchaseService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private InstoreService instoreService;
    @PostMapping("/purchase-add")
    public Result addPurchase(@RequestBody Purchase purchase,@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        purchase.setBuyTime(new Date());
        //purchase.setBuyUser(currentUser.getUserName());
        purchaseService.purchaseAdd(purchase);
        return Result.ok("新增入库成功");
    }


    @RequestMapping("/purchase-page-list")
    public Result pageQuery(Purchase purchase, Page1 page1){
        page1= purchaseService.PageQuery(purchase, page1);
        return Result.ok(page1);
    }

    @RequestMapping("/store-list")
    public Result FindStore(){
        List<Store> allStore = storeService.findAllStore();
        return Result.ok(allStore);
    }

    @DeleteMapping("/purchase-delete/{buyId}")
    public Result deleteById(@PathVariable Integer buyId){
        purchaseService.deleteById(buyId);
        return Result.ok("采购单删除成功");
    }

    @PutMapping("/purchase-update")
    public Result update(@RequestBody Purchase purchase){

        purchaseService.updatePurchase(purchase);
        return Result.ok("购物数据更新成功");
    }

    @PostMapping("/in-warehouse-record-add")
    public Result addInWarehouseRecord(@RequestBody Purchase purchase,@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);

        InStore inStore=new InStore();
        inStore.setCreateBy(currentUser.getUserId());
        inStore.setStoreId(purchase.getStoreId());
        inStore.setProductId(purchase.getProductId());
        inStore.setInNum(purchase.getFactBuyNum());

        Result result = instoreService.saveInStore(inStore, purchase.getBuyId());
        return Result.ok("入库单添加成功");
    }
}
